package oop.controller.action.user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oop.controller.action.DefaultAction;
import oop.data.User;
import oop.db.Database;

@SuppressWarnings("unused")
public class LogInAction extends UserManagerAction {

	@Override
	public void perform()
			throws Exception {

		if ("Log In".equals(request.getParameter("logIn"))) {
			int error = 0;
			if (isEmptyUserName(request, response)) {
				// empty user field
				request.setAttribute("userNameMissing", "true");
				error++;
			}
			if (isEmptyPass(request, response)) {
				// empty user field
				request.setAttribute("passMissing", "true");
				error++;
			}

			if (error > 0) {
				request.setAttribute("error", "true");
			} else {

				Connection conn;
				try {
					conn = Database.get().getConnection();
					Statement stmt = conn.createStatement();
					String sql = "SELECT user_name, user_pass, user_id "
							+ "FROM tblUser " + "WHERE user_name = '"
							+ request.getParameter("userName") + "'";
					ResultSet rs = stmt.executeQuery(sql);
					if (rs.next()) {
						// tim thay nguoi dung
						if (rs.getString("user_pass").equals(
								request.getParameter("password"))) {
							// duoc phep dang nhap
							request.getSession(true).setAttribute("username",
									request.getParameter("userName"));
							request.getSession().setAttribute("user",
									User.fetchById(rs.getInt(3)).get(0));
							request.getSession(true)
									.setAttribute("login", true);
							request.getSession(true)
								.setAttribute("notlogin", false);
							setNextAction("homepage");
						} else {
							// Sai mat khau
							request.setAttribute("wrongPass", "true");
						}
					} else {
						// Khong ton tai nguoi dung
						request.setAttribute("wrongUser", "true");
					}

				} catch (SQLException e) {
					e.printStackTrace();
					request.setAttribute("sqlError", "true");
				}
			}
		}
	}

	private boolean isEmptyUserName(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		if (isEmpty(userName))
			return true;
		return false;
	}

	private boolean isEmptyPass(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pass = request.getParameter("password");
		if (isEmpty(pass))
			return true;
		return false;
	}

}
